package com.kk.nb_car.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.kk.nb_car.remote.DistributedIDService;
import com.kk.nb_car.service.CarService;
import com.kk.nb_car.bean.Car;
import com.woniuxy.boot.common.pojo.ResultObj;
import com.woniuxy.boot.common.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: K
 * @Date: 2024/12/13
 */
@RestController("appCarController")
@RequestMapping("app/car")
public class CarController {

    @Autowired
    private CarService carService;
    @Autowired
    private DistributedIDService distributedIDService;

    /**
     * 用户绑定车辆信息
     *
     * @param car
     * @return
     */
    @PostMapping("addCar")
    public ResultObj addCar(@RequestHeader("token") String token,@RequestBody Car car) {
        //解析出用户id
        Long userId = JwtUtil.parseJwt(token);
        //设置汽车的用户id
        car.setUserId(userId);
        //调用分布式id的接口，设置车辆id为分布式id
        car.setId(distributedIDService.getDistributeID());
        //保存车辆到数据库
        carService.addCar(car);
        return ResultObj.ok();
    }

    /**
     * 用户查看自己的车辆列表
     * @param token
     * @return
     */
    @GetMapping("list")
    public ResultObj list(@RequestHeader("token") String token ) {
        //解析出用户id
        Long userId = JwtUtil.parseJwt(token);
        //根据用户id查询出车辆信息
        List<Car> list = carService.list(new LambdaQueryWrapper<Car>().eq(Car::getUserId, userId));
        return ResultObj.ok().data(list);
    }

    /**
     * 根据用户id和汽车id修改汽车部分信息，目前可修改车辆颜色，座位数
     * @param token
     * @param car
     * @return
     */
    @PostMapping("update")
    public ResultObj update(@RequestHeader("token") String token,@RequestBody Car car) {
        Long userId = JwtUtil.parseJwt(token);
        car.setUserId(userId);
        carService.update(new LambdaUpdateWrapper<Car>().eq(Car::getUserId, userId).eq(Car::getId, car.getId()).set(Car::getColor,car.getColor()).set(Car::getSeatNumber,car.getSeatNumber()));
        return ResultObj.ok();
    }

    /**
     * 根据用户id和汽车id解绑车辆，car数据库中删除记录
     * @param token
     * @param id
     * @return
     */
    @GetMapping("unbind")
    public ResultObj unbind(@RequestHeader("token") String token,@RequestParam("id")Long id) {
        Long userId = JwtUtil.parseJwt(token);
        carService.remove(new LambdaQueryWrapper<Car>().eq(Car::getUserId,userId).eq(Car::getId,id));
        return ResultObj.ok();
    }

}

